package com.process.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.process.controller.util.Code;
import com.process.controller.util.R;
import com.process.dao.pojoDao.FileDetailDao;
import com.process.dao.pojoDao.ScoreDao;
import com.process.dao.score.FinalScoreDao;
import com.process.dao.team.ProcessTaskDao;
import com.process.dao.team.ProcessTaskVoDao;
import com.process.dao.team.TopicVoDao;
import com.process.domain.publi.FileDetail;
import com.process.domain.score.FinalScore;
import com.process.domain.score.MemberScore;
import com.process.domain.score.Score;
import com.process.domain.team.ClassScore;
import com.process.domain.team.ProcessTask;
import com.process.domain.team.ProcessTaskVo;
import com.process.service.score.ScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @ClassName: ScoreController
 * @Author: 殷凡卓
 * @Date: 2023/5/8 10:43
 */
@RestController
@Slf4j
@RequestMapping("score")
public class ScoreController {
    @Autowired
    private ScoreService scoreService;

    @Autowired
    private ProcessTaskVoDao processTaskVoDao;
    @Autowired
    private ProcessTaskDao processTaskDao;
    @Autowired
    private FileDetailDao fileDetailDao;
    @Autowired
    private ScoreDao scoreDao;
    @Autowired
    private FinalScoreDao finalScoreDao;
    @Autowired
    private TopicVoDao topicVoDao;

    @GetMapping("processTask")
    public R getProcessTask(ServletRequest servletRequest) {
        String stuPhone = (String) servletRequest.getAttribute("username");
        List<ProcessTaskVo> processTaskVos = processTaskVoDao.selectProcessFinallTaskByStudentPhone(stuPhone);
        return new R(Code.GET_OK, processTaskVos, "学生查看需要互评的任务");
    }

    /**
     * 学生查看需要打分的人
     *
     * @param processId
     * @param servletRequest
     * @return
     */
    @GetMapping("stuGetMouse/{processId}")
    public R getProcessTask(@PathVariable long processId, ServletRequest servletRequest) {
        String stuPhone = (String) servletRequest.getAttribute("username");

        ProcessTask processTask = processTaskDao.selectOne(new LambdaQueryWrapper<ProcessTask>().eq(ProcessTask::getProcessId, processId));
        Date scoreStart = processTask.getScoreStart();
        Date scoreEnd = processTask.getScoreEnd();
        Date now = new Date();
        if (now.before(scoreEnd) && now.after(scoreStart)) {
            List<Score> myMouses = scoreService.getMyMouses(stuPhone, processId);

            for (Score mouse : myMouses) {
                FileDetail one = fileDetailDao.selectOne(new LambdaQueryWrapper<FileDetail>()
                        .eq(FileDetail::getProcessId, processId)
                        .eq(FileDetail::getSubmitter, mouse.getAppraiseePhone()));

                if (one != null)
                    mouse.setFilePath(one.getFilename());
                else
                    mouse.setFilePath(null);
            }


            return new R(Code.GET_OK, myMouses, "打分时间验证通过，学生查看我需要批改的人");
        } else {

            return new R(Code.GET_ERR, null, "当前不是打分指定时间，不能使用");
        }
    }

    /**
     * 教师查看学生情况
     * author :殷凡卓
     *
     * @param practicalId
     * @param servletRequest
     * @return
     */
    @GetMapping("classTopicAoDetail/{practicalId}")
    public R getClassTopicAoDetail(@PathVariable long practicalId, ServletRequest servletRequest) {
        List<ClassScore> classScores = topicVoDao.selectInnerTopicAoDetail(practicalId);

        return new R(Code.GET_OK, classScores, "教师打分查看班级详情");
    }

    /**
     * 学生打分
     *
     * @param fraction
     * @param processId
     * @param appraiseePhone
     * @param servletRequest
     * @return
     */
    @GetMapping("stuGetMouse/{processId}/{appraiseePhone}/{fraction}")
    public R getProcessTask(@PathVariable long fraction, @PathVariable long processId, @PathVariable String appraiseePhone, ServletRequest servletRequest) {
        String stuPhone = (String) servletRequest.getAttribute("username");

        Score one = scoreService.getOne(new LambdaQueryWrapper<Score>()
                .eq(Score::getProcessId, processId)
                .eq(Score::getAppraiseePhone, appraiseePhone)
                .eq(Score::getRaterPhone, stuPhone));

        Date scoreTime = one.getScoreTime();
        if (scoreTime != null)
            return new R(Code.GET_ERR, one, "已打分，勿重复打分");


        LambdaUpdateWrapper<Score> updateWrapper = new LambdaUpdateWrapper<Score>()
                .eq(Score::getProcessId, processId)
                .eq(Score::getAppraiseePhone, appraiseePhone)
                .eq(Score::getRaterPhone, stuPhone)
                .set(Score::getFraction, fraction)
                .set(Score::getScoreTime, new Date());

        boolean update = scoreService.update(updateWrapper);

        return new R(Code.GET_OK, update, "打分成功：" + fraction);
    }

    /**
     * 教师查看学生打分
     *
     * @param processId
     * @param servletRequest
     * @return
     */
    @GetMapping("/{processId}/{stuPhone}")
    public R setScore(@PathVariable long processId, @PathVariable String stuPhone, ServletRequest servletRequest) {
        //获取我的电话号码
//        String username = (String) servletRequest.getAttribute("username");
        List<Score> scores = scoreDao.selectList(new LambdaQueryWrapper<Score>()
                .eq(Score::getProcessId, processId)
                .eq(Score::getAppraiseePhone, stuPhone));
        MemberScore memberScore = new MemberScore();

        FileDetail one = fileDetailDao.selectOne(new LambdaQueryWrapper<FileDetail>()
                .eq(FileDetail::getSubmitter, stuPhone)
                .eq(FileDetail::getProcessId, processId));

        if (one == null) {

            return new R(Code.GET_ERR, memberScore, "学生未提交最终报告,互评分为0");
        } else if (one.getId() == null || one.getOriginalFilename() == null) {

            return new R(Code.GET_ERR, memberScore, "学生未提交最终报告，互评分为0");
        }

        int numPeople = scores.size();
        int addAll = 0;

        if (numPeople > 0) {
            memberScore.setScore_1(scores.get(0).getFraction());
            addAll += scores.get(0).getFraction();
            numPeople--;
        }
        if (numPeople > 0) {
            memberScore.setScore_2(scores.get(1).getFraction());
            addAll += scores.get(1).getFraction();
            numPeople--;
        }
        if (numPeople > 0) {
            memberScore.setScore_3(scores.get(2).getFraction());
            addAll += scores.get(2).getFraction();
            numPeople--;
        }
        if (numPeople > 0) {
            memberScore.setScore_4(scores.get(3).getFraction());
            addAll += scores.get(3).getFraction();
        }


        long finalScore = addAll / scores.size();
        memberScore.setScore_final(finalScore);


        memberScore.setReportId(one.getId());
        memberScore.setOriginalFilename(one.getOriginalFilename());
        return new R(Code.GET_OK, memberScore, "教师查看学生打分");


    }


    /**
     * 教师打分
     *
     * @param servletRequest
     * @return
     */
    @PostMapping("finallProcessTask")
    public R setFinallScore(@RequestBody FinalScore finalScore, ServletRequest servletRequest) {
        String stuPhone = (String) servletRequest.getAttribute("username");
        if (finalScore.getReportId() == null)
            return new R(Code.SAVE_ERR, null, "请先选择学生");


        int insert = finalScoreDao.insert(finalScore);
        if (insert != 0)
            return new R(Code.GET_OK, insert, "教师打分");
        else
            return new R(Code.GET_ERR, insert, "打分失败");
    }

}
